package com.ymj.netty.client;

import com.alibaba.fastjson.JSON;
import com.ymj.netty.client.handler.BizClientHandler;
import com.ymj.netty.common.ClientRequest;
import com.ymj.netty.common.Response;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 *  @Description: tcp长连接Client
 *  @author: yanmj
 *  @Date: 2020-06-07
 */
public class TcpClient {

    static final Bootstrap bootstrap = new Bootstrap();
    static ChannelFuture future = null;
    static{
        EventLoopGroup group = new NioEventLoopGroup(1);
        bootstrap.group(group)
                .remoteAddress(new InetSocketAddress("127.0.0.1",8081))
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(65535, Delimiters.lineDelimiter()));
                        socketChannel.pipeline().addLast(new StringDecoder());
                        socketChannel.pipeline().addLast(new IdleStateHandler(60,45,20, TimeUnit.SECONDS));
                        socketChannel.pipeline().addLast(new BizClientHandler());
                        socketChannel.pipeline().addLast(new StringEncoder());

                    }
                });

        try {
            future = bootstrap.connect().sync();
            //下面这一句需要注释掉，不然主线程会一直同步在这里等待channel关闭，干不了其他事情
            //future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }


    /**
     * 通过此方法使用netty客户端向服务端发送请求
     * @param request
     * @return
     */
    public static Response send(ClientRequest request){
        ClientFuture clientFuture = new ClientFuture(request);
        future.channel().writeAndFlush(JSON.toJSONString(request));
        future.channel().writeAndFlush("\r\n");
        Response response = clientFuture.get();
        future.channel().close();
        return response;
    }

}
